import { USER_TOKEN } from '@/constants/local-storage-key-const';
// import { decryptData, encryptData } from './encrypt';
// import { useUserStore } from '@/store/modules/system/user';

let baseUrl = "https://da.yueyangtech.com.cn/couple"
// #ifdef H5
baseUrl = '/app'
// #endif

function getUserToken() {
  let token = uni.getStorageSync(USER_TOKEN);
  if (token) {
    return token;
  }
  return '';
}

/**
 * 通用请求封装
 */
export const request = function (url, method, data, toast=true) {
  return new Promise((resolve, reject) => {
    uni.request({
      url: baseUrl + url,
      data: data,
      method: method,
      header: {
        'token': getUserToken(),
      },
      success: (response) => {
		if(response.statusCode == 200){
			const res = response.data;
			if (res.code && res.code !== 200) {
			  if(toast){
				  uni.showToast({
				    title: res.msg,
				    icon: 'none',
				  });
			  }
			  if (res.code === 401) {
			    // useUserStore().clearUserLoginInfo();
			    // uni.navigateTo({ url: '/pages/login/login' });
			  }
			  reject(res);
			} else {
			  resolve(res.data);
			}
		}else{
			uni.showToast({
				title:'网络异常',
				icon:'none'
			})
			reject()
		}
      },
      fail: (error) => {
        reject(error);
      },
    });
  });
};

export const getRequest = (url, toast=true) => {
  return request(url, 'GET',{},toast);
};

export const postRequest = (url, data, toast=true) => {
  return request(url, 'POST', data, toast);
};

/**
 * 加密请求参数的post请求
 */
export const postEncryptRequest = (url, data) => {
  return request(url, 'POST', { encryptData: encryptData(data) });
};

export const uploadRequest = function (filePath, folder) {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: baseUrl + '/v1/upload',
      filePath,
      header: {
        'token': getUserToken(),
      },
      name: 'file',
      formData: folder,
      success: (response) => {
		if(response.statusCode == 200){
			const res = JSON.parse(response.data.replace('\uFEFF', ''));
			if (res.code && res.code !== 200) {
			  uni.showToast({
			    title: res.msg,
			    icon: 'none',
			  });
			  reject(response.data);
			} else {
			  resolve(res);
			}
		}else{
			uni.showToast({
				title:'网络异常',
				icon:'none'
			})
			reject()
		}
      },
      fail: (error) => {
        reject(error);
      },
    });
  });
};
